<template>
  <div class="admin-category-page">
    <el-container>
      <!-- 头部 -->
      <el-header class="page-header">
        <div class="header-left">
          <h2>分类管理</h2>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增分类
          </el-button>
        </div>
      </el-header>

      <!-- 内容区域 -->
      <el-main>
        <el-card>
          <el-table
            v-loading="loading"
            :data="categoryList"
            stripe
            row-key="id"
            :tree-props="{ children: 'children' }"
            default-expand-all
            style="width: 100%"
          >
            <el-table-column prop="categoryName" label="分类名称" min-width="200" />
            <el-table-column prop="sortOrder" label="排序" width="100" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column label="商品数量" width="100">
              <template #default="{ row }">
                <span>{{ row.productCount || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>

    <!-- 分类编辑对话框 -->
    <CategoryDialog
      v-model="dialogVisible"
      :category-id="editingCategoryId"
      :parent-categories="categoryList"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCategoryTree, deleteCategory } from '@/api/category'
import CategoryDialog from './components/CategoryDialog.vue'

const loading = ref(false)
const categoryList = ref([])
const dialogVisible = ref(false)
const editingCategoryId = ref(null)

// 加载分类列表
const loadCategories = async () => {
  loading.value = true
  try {
    const res = await getCategoryTree()
    if (res.code === 200 && res.data) {
      categoryList.value = res.data
    } else {
      ElMessage.error(res.message || '加载分类列表失败')
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  editingCategoryId.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  editingCategoryId.value = row.id
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    // 检查是否有子分类
    if (row.children && row.children.length > 0) {
      ElMessage.warning('该分类下还有子分类，无法删除')
      return
    }

    // 检查是否有商品
    if (row.productCount && row.productCount > 0) {
      ElMessage.warning('该分类下还有商品，无法删除')
      return
    }

    await ElMessageBox.confirm(`确定要删除分类"${row.categoryName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteCategory(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadCategories()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 对话框成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadCategories()
}

// 初始化
onMounted(() => {
  loadCategories()
})
</script>

<style lang="scss" scoped>
.admin-category-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }
}
</style>
